package com.hps.demo;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.CuratorWatcher;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.framework.recipes.cache.NodeCache;
import org.apache.curator.framework.recipes.cache.NodeCacheListener;
import org.apache.curator.framework.recipes.cache.PathChildrenCache;
import org.apache.curator.framework.recipes.cache.PathChildrenCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;

/**
 * @Author hps
 * @Description:
 * @Date Created in 17:23 2019/7/11
 */
public class Test {

    private static CuratorFramework client = null;

    public static void main(String[] args) throws Exception {
         client = CuratorFrameworkFactory.builder()
                 .connectString("192.168.26.143:2181")
                 .retryPolicy(new ExponentialBackoffRetry(1000, 3))
                 .namespace("hps")
                 .build();
         client.start();

        getData("/test/node1");

        create("/test/node1/child9");
        System.in.read();
    }

    private static void create(String path) throws Exception {
        String s = client.create().creatingParentContainersIfNeeded().withMode(CreateMode.PERSISTENT).withACL(ZooDefs.Ids.OPEN_ACL_UNSAFE).forPath(path, "hello".getBytes());
        System.out.println(s);
    }

    private static void getData(String path) throws Exception {
        byte[] bytes = client.getData().forPath(path);
        System.out.println(new String(bytes));
        registryWatch(path);

        CuratorFrameworkState state = client.getState();
        System.out.println(state);
    }

    private static void setData(String path) throws Exception {
        client.setData().forPath(path, "test".getBytes());
    }

    private static void registryWatch(final String path) throws Exception {
        PathChildrenCache nodeCache=new PathChildrenCache(client,path,true);
        PathChildrenCacheListener nodeCacheListener= (curatorFramework1, pathChildrenCacheEvent) -> {
            System.out.println("客户端收到节点变更的事件");
        };
        nodeCache.getListenable().addListener(nodeCacheListener);
        nodeCache.start();

    }

}
